#
# @lc app=leetcode.cn id=968 lang=python
#
# [968] 监控二叉树
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def minCameraCover(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        self.num = 0
        root_status = self.loop(root)
        if root_status == 0:
            return self.num+1
        else:
            return self.num

    def loop(self, node):
        if node is None:
            return 2

        left = self.loop(node.left)
        right = self.loop(node.right)
        if left == 2 and right == 2:
            return 0
        elif (left == 1 and right == 2) or (left == 2 and right == 1):
            return 2
        elif left == 1 and right == 1:
            return 2
        elif (left == 0 and right == 2) or (left == 2 and right == 0):
            self.num += 1
            return 1
        elif (left == 0 and right == 1) or (left == 1 and right == 0):
            self.num += 1
            return 1
        elif left == 0 and right == 0:
            self.num += 1
            return 1


        
# @lc code=end

